<?php
class CommonAction extends CheFieldAction {

	public function _initialize() {
		$this->_inject_check(1);//调用过滤函数

		// 用户权限检查
		if (C ( 'USER_AUTH_ON' ) && !in_array(MODULE_NAME,explode(',',C('NOT_AUTH_MODULE')))) {
			import ( '@.ORG.RBAC' );
			if (! RBAC::AccessDecision ()) {
				//检查认证识别号
				if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
					//跳转到认证网关
					redirect ( PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
				}
				// 没有权限 抛出错误
				if (C ( 'RBAC_ERROR_PAGE' )) {
					// 定义权限错误页面
					redirect ( C ( 'RBAC_ERROR_PAGE' ) );
				} else {
					if (C ( 'GUEST_AUTH_ON' )) {
						$this->assign ( 'jumpUrl', PHP_FILE . C ( 'USER_AUTH_GATEWAY' ) );
					}
					// 提示错误信息
					$this->error ( L ( '_VALID_ACCESS_' ) );
				}
			}
		}


	}

	protected function _Gly_checkUser(){
		//后台权限
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$_SESSION = array();
			$bUrl = __APP__.'/Public/login';
			$this->_boxx($bUrl);
			exit;
		}
		$fck = M('fck');
		$mapp				=   array();
		$mapp['id']			= $_SESSION[C('USER_AUTH_KEY')];
		$mapp['is_jb']	= array('gt',0);
		$field = 'id,user_id';
        $rs = $fck->where($mapp)->field($field)->find();
        if(!$rs){
        	$_SESSION = array();
			$bUrl = __APP__.'/Public/login';
			$this->_boxx($bUrl);
			exit;
        }
		unset($fck,$mapp,$rs);
	}


	protected function _Admin_checkUser(){
        //后台权限
        if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
            $_SESSION = array();
            $bUrl = __APP__.'/Public/login';
            $this->_boxx($bUrl);
            exit;
        }
        $fck = M('fck');
        $admid			= $_SESSION[C('USER_AUTH_KEY')];
//		$mapp				=   array();
//		$mapp['id']			= $_SESSION[C('USER_AUTH_KEY')];
//		$mapp['is_boss']	= array('gt',0);
        $field = 'id,user_id';
        $rs = $fck->where('id='.$admid.' and (is_boss>0 or (is_boss=0 and is_aa>0))')->field($field)->find();
        if(!$rs){
            $_SESSION = array();
            $bUrl = __APP__.'/Public/login';
            $this->_boxx($bUrl);
            exit;
        }
        unset($fck,$mapp,$rs);
	}
	// 检查用户是否登录
	protected function _checkUser() {
		if(!isset($_SESSION[C('USER_AUTH_KEY')])) {
			$this->LinkOut();
			exit;
		}
//		$this->check_order_isout();
		
		$this->_user_mktime($_SESSION['UserMktimes']);
		$User = M ('fck');


		//生成认证条件
        $mapp            =   array();
		// 支持使用绑定帐号登录
		//管理员编号，证明
		$mapp['id']    = $_SESSION[C('USER_AUTH_KEY')];
		$mapp['user_id']	= $_SESSION['loginUseracc'];
		$field = 'user_id,password,user_type,is_lock';
        $authInfoo = $User->where($mapp)->field($field)->find();
        if(false == $authInfoo) {
            $this->LinkOut();
			exit;
        }else {
       		if($authInfoo['is_lock'] == 1){
				echo "<script language=javascript>";
				echo 'alert("==您的账户已锁定！==");';
				echo "</script>";
				$this->LinkOut();
			}
			//是否允许一个用户同时多人在线！
        	$fee = M ('fee');
			$fee_rs = $fee->field('i3,str27')->find(1);
			$user_type = 0;
			if ($fee_rs['user_type'] == 1){
				if ($_SESSION['login_user_type'] != $authInfoo['user_type']){
					$user_type = 1;
				}
			}
			if($fee_rs['i3'] == 1){
				if ($_SESSION[C('USER_AUTH_KEY')] != 1){
					echo "<script language=javascript>";
					echo 'alert("=='.$fee_rs['str27'].'==");';
					echo "</script>";
					$this->LinkOut();
                }

			}
			unset($fee,$fee_rs);
        	$mpwd = md5($authInfoo['user_id'].'wodetp_new_1012!@#' . $authInfoo['password'] . $_SERVER['HTTP_USER_AGENT']);
			if ($mpwd != $_SESSION['login_sf_list_u'] || $user_type == 1){
//				$this->LinkOut();
//				exit;
			}
		}
	}
	//检测登录是否超时
	protected function _user_mktime($onlinetime){
		$new_time = mktime();
		if ($new_time - $onlinetime > '72000'){
			$this->LinkOut();
			exit;
		}else{
			$_SESSION['UserMktimes'] = mktime();
		}
	}
	
	//检测登录是否超时
	protected function check_order_isout(){
		$id  = $_SESSION[C('USER_AUTH_KEY')];
		$fck = M ('fck');
		$cashpp = M ('cashpp');
		$nowdate = strtotime(date('c'));
		
		$fee = M('fee');
		$fee_rs = $fee->field('s12,str9')->find();
		$fee_s12 = $fee_rs['s12'];
		$fee_str9 = $fee_rs['str9'];
		
		$buylasttime = $nowdate - $fee_s12*3600;
		$selllasttime = $nowdate - $fee_str9*3600;
		
		if($id>1){
			//未打款检查
			$mapp            =   array();
			$mapp['uid']    = $id;
			$mapp['is_buy']	= 1;
			$mapp['is_pay'] = 0;
			$mapp['bdt']	= array('lt',$buylasttime);
			$buych = $cashpp ->where($mapp)->select();
			if($buych){
				$fck->execute("UPDATE __TABLE__ SET `is_lock`=1 where id>1 and id=".$id);
				$this->LinkOut();
			}
			
			//收款未确认检查
			$map           =   array();
			$map['bid']    = $id;
			$map['is_buy'] = 2;
			$map['is_pay'] = 0;
			$map['bdt']	   = array('lt',$selllasttime);
			$sellch = $cashpp ->where($map)->select();
			if($sellch){
				$fck->execute("UPDATE __TABLE__ SET `is_lock`=1 where id>1 and id=".$id);
				$this->LinkOut();
			}
		}
	}
	
	public function LinkOut(){
		$_SESSION = array();
		$this->display('Public:LinkOut');
	}
	//处理结果函数 (结果，事件，跳转url，跳转时间单位为秒)
	protected function _box($dz=0,$list='',$url='',$ms=3,$cgs=0){
		if ($dz == 1){
			$dz = '操作成功!';
		}else{
			$dz = '操作失败!';
		}
		if ($cgs == 1){
			$cgs = 'parent.';
		}else{
			$cgs = '';
		}
		$lists = array();
		$lists['Title'] = $list;
		$lists['Url'] = $url;
		$lists['ms'] = $ms;
		$lists['dz'] = $dz;
		$lists['cgs'] = $cgs;
		$this->assign('list',$lists);
		$this->display('Public:box');
	}
	protected function _box1($dz=0,$list='',$url='',$ms=3,$cgs=0){
		if ($dz == 1){
			$dz = '操作成功!';
		}else{
			$dz = '操作失败!';
		}
		if ($cgs == 1){
			$cgs = 'parent.';
		}else{
			$cgs = '';
		}
		$lists = array();
		$lists['Title'] = $list;
		$lists['Url'] = $url;
		$lists['ms'] = $ms;
		$lists['dz'] = $dz;
		$lists['cgs'] = $cgs;
		$this->assign('list',$lists);
		$this->display('Public:box1');
	}
	protected function _box2($dz=0,$list='',$url='',$ms=3,$cgs=0){
		if ($dz == 1){
			$dz = '操作成功!';
		}else{
			$dz = '操作失败!';
		}
		if ($cgs == 1){
			$cgs = 'parent.';
		}else{
			$cgs = '';
		}
		$lists = array();
		$lists['Title'] = $list;
		$lists['Url'] = $url;
		$lists['ms'] = $ms;
		$lists['dz'] = $dz;
		$lists['cgs'] = $cgs;
		$this->assign('list',$lists);
		$this->display('Public:box2');
	}
	//页面跳转
	protected function _boxx($url=''){
		echo "<script> location.href='{$url}' </script>";
	}
	//过滤函数
	protected function _inject_check($sql_str=0) {
			//合并$_POST 和 $_GET
			foreach ($_GET as $get_key => $get_var){
				$get[strtolower($get_key)] = $get_var;
			}
			/* 过滤所有POST过来的变量 */
			foreach ($_POST as $post_key => $post_var){
			  $post[strtolower($post_key)] = $post_var;
			}
		//需要过滤的数据
		if ($sql_str == 0){
			$GetPost = 'select|insert|update|delete|union|into|load_file|outfile|and';
		}else{
			$GetPost = 'select|insert|update|delete|\'|\/\*|\*|\.\.\/|\.\/|union|into|load_file|outfile|\(|\)|\<|\>|and|chr|char';
		}

        foreach ($post as $post_key => $sql_str){
			$check = eregi($GetPost,$sql_str);// 进行过滤
			if ($check){
				$this->error('输入内容不合法，请重新输入！');
				exit();
			}
		}
		foreach ($get as $post_key => &$sql_str){
            $check = eregi($GetPost,$sql_str);// 进行过滤
			if ($check){
				$this->error('输入内容不合法，请重新输入！');
				exit();
			}
		}
		//xss
        foreach ($_GET as $key => &$value){
            $value=$this->remove_xss($value);
        }
        foreach ($_POST as $key => &$value){
            $value=$this->remove_xss($value);
        }
	}

	protected function _levelConfirm(&$HYJJ,$HYid=1){
		$HYJJ = array();
		$User = M ('fee');
		$fee_rs = $User->find(1);
		$fee_s1 = explode('|',$fee_rs['s10']);
		$HYJJ[1] = $fee_s1[0];
		$HYJJ[2] = $fee_s1[1];
		$HYJJ[3] = $fee_s1[2];
		$HYJJ[4] = $fee_s1[3];
		$HYJJ[5] = $fee_s1[4];
 		$HYJJ[6] = $fee_s1[5];
	}
	
	protected function _getLevelConfirm(&$HYJJ,$HYid=1){
		$HYJJ = array();
		$HYJJ[0] = "普卡";
		$HYJJ[1] = "金卡";
		$HYJJ[2] = "钻卡";
		$HYJJ[3] = "报单中心";
		$HYJJ[4] = "四星";
	}

	public function index() {
		//列表过滤器，生成查询Map对象
		$map = $this->_search ();
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
		return;
	}
	/**
     +----------------------------------------------------------
	 * 取得操作成功后要返回的URL地址
	 * 默认返回当前模块的默认操作
	 * 可以在action控制器中重载
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	function getReturnUrl() {
		return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param string $name 数据对象名称
     +----------------------------------------------------------
	 * @return HashMap
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _search($name = '') {
		//生成查询条件
		if (empty ( $name )) {
			$name = $this->getActionName();
		}
		$name=$this->getActionName();
		$model = D ( $name );
		$map = array ();
		foreach ( $model->getDbFields () as $key => $val ) {
			if (isset ( $_REQUEST [$val] ) && $_REQUEST [$val] != '') {
				$map [$val] = $_REQUEST [$val];
			}
		}
		return $map;
	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param Model $model 数据对象
	 * @param HashMap $map 过滤条件
	 * @param string $sortBy 排序
	 * @param boolean $asc 是否正序
     +----------------------------------------------------------
	 * @return void
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	 //==============================================分页函数
	protected function _list($model, $map, $sortBy = '', $asc = false) {
		//排序字段 默认为主键名
		if (isset ( $_REQUEST ['_order'] )) {
			$order = $_REQUEST ['_order'];
		} else {
			$order = ! empty ( $sortBy ) ? $sortBy : $model->getPk ();
		}
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset ( $_REQUEST ['_sort'] )) {
			$sort = $_REQUEST ['_sort'] ? 'asc' : 'desc';
		} else {
			$sort = $asc ? 'asc' : 'desc';
		}
		//取得满足条件的记录数
		$count = $model->where ( $map )->count ( 'id' );
		if ($count > 0) {
			import ( "@.ORG.Page" );
			//创建分页对象
			if (! empty ( $_REQUEST['listRows'] )) {
				$listRows = $_REQUEST['listRows'];
			} else {
				$listRows = '';
			}
			$p = new Page ( $count, 10 );
			//分页查询数据

			$voList = $model->where($map)->order( "`" . $order . "` " . $sort)->limit($p->firstRow . ',' . $p->listRows)->select();
			//echo $model->getlastsql();
			//分页跳转的时候保证查询条件
			foreach ( $map as $key => $val ) {
				if (! is_array ( $val )) {
					$p->parameter .= "$key=" . urlencode ( $val ) . "&";
				}
			}
			//会员等级 开始=================
			$i = 1;
			$HYJJ = array();
			$HYoo = array();
			$this->_levelConfirm($HYJJ,1);
			foreach($voList as $voo){
				$HYoo[$i][0] = $HYJJ[$voo['u_level']];
				$i++;
			}
			$this->assign('voo',$HYoo);
			//会员等级 结束=================

			//分页显示
			$page = $p->show ();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			//模板赋值显示
			$this->assign ( 'list', $voList );
			$this->assign ( 'sort', $sort );
			$this->assign ( 'order', $order );
			$this->assign ( 'sortImg', $sortImg );
			$this->assign ( 'sortType', $sortAlt );
			$this->assign ( "page", $page );
		}
		Cookie::set ( '_currentUrl_', __SELF__ );
		return;
	}

	protected function _2Mal($name=0,$wei=0) {
		//格式化数字，保留小数位数
		$map = sprintf('%.'.$wei.'f', (float)$name);
		return $map;
	}
	public function _Config_name() {
		header("Content-Type:text/html; charset=utf-8");
		//调用系统参数
		$System_namex    = C('System_namex');        //系统名字
		//$System_bankx    = C('System_bankx');        //银行名字
		$User_namex      = C('User_namex');
		$Nick_namex      = C('Nick_namex');
		//$Member_Level    = C('Member_Level');       //会员级别名称
		//$Member_Money    = C('Member_Money');       //注册金额
		//$Member_Single   = C('Member_Single');      //会员级别单数



		$this->assign ('System_namex',$System_namex);
		//$this->assign ('System_bankx',$System_bankx);
		$this->assign ('User_namex',$User_namex);
		$this->assign ('Nick_namex',$Nick_namex);
		//$this->assign ('Member_Level',$Member_Level);
		//$this->assign ('Member_Money',$Member_Money);
		//$this->assign ('Member_Single',$Member_Single);
	}
	
	//三轨小公排
// 	public function gongpaixtsmall($uid){
// 		$fck = M ('fck');
// 		$mouid=$uid;
//         $field = 'id,user_id,p_level,p_path,u_pai';
//         $where = 'is_pay>0 and (p_path like "%,'.$mouid.',%" or id='.$mouid.')';

// 		$re_rs = $fck ->where($where)->order('p_level asc,u_pai asc')->field($field)->select();
// 		$fck_where = array();
// 		foreach($re_rs as $vo){
// 			$faid=$vo['id'];
// 			$fck_where['is_pay']   = array('egt',0);
// 			$fck_where['father_id']   = $faid;
// 			$count = $fck->where($fck_where)->count();
// 			if ( is_numeric($count) == false){
// 	            $count = 0;
// 	        }
// 			if ($count<3){
// 				$father_id=$vo['id'];
// 				$father_name=$vo['user_id'];
// 				$TreePlace=$count;
// 				$p_level=$vo['p_level']+1;
// 				$p_path=$vo['p_path'].$vo['id'].',';
// 				$u_pai=$vo['u_pai']*3+$TreePlace-1;

// 				$arry=array();
// 				$arry['father_id']=$father_id;
// 				$arry['father_name']=$father_name;
// 				$arry['treeplace']=$TreePlace;
// 				$arry['p_level']=$p_level;
// 				$arry['p_path']=$p_path;
// 				$arry['u_pai']=$u_pai;
// 				return $arry;
// 				break;
// 			}
// 		}
// 	}
	
	//双轨小公排
	public function gongpaixtsmall($uid){
		$fck = M ('fck');
		$mouid=$uid;
		$field = 'id,user_id,p_level,p_path,u_pai';
		$where = 'is_pay>0 and (p_path like "%,'.$mouid.',%" or id='.$mouid.')';
	
		$re_rs = $fck ->where($where)->order('p_level asc,u_pai asc')->field($field)->select();
		$fck_where = array();
		foreach($re_rs as $vo){
			$faid=$vo['id'];
			$fck_where['is_pay']   = array('egt',0);
			$fck_where['father_id']   = $faid;
			$count = $fck->where($fck_where)->count();
			if ( is_numeric($count) == false){
				$count = 0;
			}
			if ($count<2){
				$father_id=$vo['id'];
				$father_name=$vo['user_id'];
				$TreePlace=$count;
				$p_level=$vo['p_level']+1;
				$p_path=$vo['p_path'].$vo['id'].',';
				$u_pai=$vo['u_pai']*2+$TreePlace;
	
				$arry=array();
				$arry['father_id']=$father_id;
				$arry['father_name']=$father_name;
				$arry['treeplace']=$TreePlace;
				$arry['p_level']=$p_level;
				$arry['p_path']=$p_path;
				$arry['u_pai']=$u_pai;
				return $arry;
				break;
			}
		}
	}
	

	protected function _cheakPrem()
    {
        //权限
        $fck = M ('fck');
        $id = $_SESSION[C('USER_AUTH_KEY')];
        $frs = $fck ->field('prem') ->find($id);
        $arr = explode(',',$frs['prem']);
        for ($i=1;$i<=30;$i++){
            if (in_array($i,$arr)){
                $arss[$i] = 1;
            }else{
                $arss[$i] = 0;
            }
        }
        return $arss;
    }
    
    public function check_us_gq($type=0){
//		$fck = M('fck');
//		$mapp['id']    = $_SESSION[C('USER_AUTH_KEY')];
//		$field = 'user_id,is_lockqd';
//		$aurs = $fck->where($mapp)->field($field)->find();
//		if(false == $aurs) {
//			$this->LinkOut();
//			exit;
//		}else{
//			if($aurs['is_lockqd']==1){
//				echo "<script language=javascript>";
//				echo 'alert("==您的账户已过期，请续费后在使用==");';
//				if($type==0){
//					echo 'history.back(-1);';
//				}
//				echo "/<script>";
//				if($type==0){
//					exit;
//				}
//			}
//		}
//		unset($fck,$mapp,$aurs);
    }
    
	//======================================奖金结算
    public function  _clearing(){
		//参数
		$times = M ('times');  //结算时间表
		$fck = D ('Fck');

		//以下写进资金表
		$nowdate = strtotime(date('Y-m-d'))+3600*24-1;
//		$nowdate = time();
        $settime_two['benqi'] = $nowdate;
        $settime_two['type']  = 0;
        $trs = $times->where($settime_two)->find();  //找出本期结算时间
        if (!$trs){  //不存在本期
            $rs3 = $times->where('type=0')->order('id desc')->find(); //找出上期结算时间
            if ($rs3){
				$data['shangqi']  = $rs3['benqi'];
				$data['benqi']    = $nowdate;
				$data['is_count'] = 0;
				$data['type']     = 0;
			}else{  //不存在上期,创建第一期
				$data['shangqi']  = strtotime('2010-01-01');
				$data['benqi']    = $nowdate;
				$data['is_count'] = 0;
				$data['type']     = 0;
			}
			unset($rs3);
			
			$times->add($data);  // times表 添加本期结算

		}else{
			$data['shangqi'] = $trs['shangqi'];
			$data['benqi']   = $trs['benqi'];
		}  //整理结算时间

		$times_time = $data['shangqi'];

		$fck->execute("UPDATE __TABLE__ SET `b0`=b1+b2+b3");

		//奖金汇总
		$fck->quanhuizong();

		$bonus = M ('bonus');
		$twhere = array();
		$twhere['type'] = 0;
		$trs_two = $times->where($twhere)->order('id desc')->field('id')->find();  //找出times表所有记录并倒序,只取id字段

		$where_two = array();
		$data2 = array();
		$where_two['did'] = $trs_two['id'];  //本期结算 times表id
		$fwhere = array();
		$fwhere['b0'] = array('neq',0);       //这一期总奖金大于0
		$fwhere['is_tj'] = array('eq',0);    //统计占用
		$fwhere['is_pay'] = array('gt',0);   //已开通的会员
		$rs = $fck ->where($fwhere)->field('*')->order('id asc')->select();
		foreach ($rs as $rss){
			$my_b = $rss['b0'];
			$my_id = $rss['id'];
			$myww = "id=".$my_id." and b0=".$my_b." and is_tj=0";
			$result = $fck -> execute("update __TABLE__ set zjj=zjj+b0,is_tj=1,agent_use=agent_use+".$my_b." where ".$myww);
			if($result){
				$where_two['uid'] = $rss['id'];
				$bonus_rs = $bonus->where($where_two)->find();  //查找是否存在本期结算记录
				if (!$bonus_rs){
					$data2['e_date']   = $data['benqi'];
					$data2['s_date']   = $data['shangqi'];
					$data2['user_id']  = $rss['user_id'];
					$data2['did']      = $trs_two['id'];
					$data2['uid']      = $rss['id'];
					$data2['b0']       = $rss['b0'];
					$data2['b1']       = $rss['b1'];
					$data2['b2']       = $rss['b2'];
					$data2['b3']       = $rss['b3'];
					$data2['b4']       = $rss['b4'];
					$data2['b5']       = $rss['b5'];
					$data2['b6']       = $rss['b6'];
					$data2['b7']       = $rss['b7'];
					$data2['b8']       = $rss['b8'];
					$data2['b9']       = $rss['b9'];
					$bonus->add($data2);  // bonus 奖金表新增本期记录
				}else{
					$sql  = "`b0`=b0+". $rss['b0'] .",";
					$sql .= "`b1`=b1+". $rss['b1'] .",";
					$sql .= "`b2`=b2+". $rss['b2'] .",";
					$sql .= "`b3`=b3+". $rss['b3'] .",";
					$sql .= "`b4`=b4+". $rss['b4'] .",";
					$sql .= "`b5`=b5+". $rss['b5'] .",";
					$sql .= "`b6`=b6+". $rss['b6'] .",";
					$sql .= "`b7`=b7+". $rss['b7'] .",";
					$sql .= "`b8`=b8+". $rss['b8'] .",";
					$sql .= "`b9`=b9+". $rss['b9'] ."";
					$bonus -> query("update __TABLE__ set ". $sql ." where `id`=". $bonus_rs['id']);  //bonus 奖金表本期记录++
				}
				$fck -> query("update __TABLE__ set b0=0,b1=0,b2=0,b3=0,b4=0,b5=0,b6=0,b7=0,b8=0,b9=0,is_tj=0 where id=".$my_id);
			}
        }
		$fck->_addBonus();
		unset($fck,$times,$trs,$settime_two,$bonus,$twhere,$trs_two,$data2,$fwhere,$rs,$data);
	}
    

    //引用编辑器
	public function us_fckeditor($inputid,$value,$height,$width='100%')
	{
		//引用编辑器库类
		import ( "@.ORG.FCKeditor.fckeditor" );  //导入分页类
//		vendor("FCKeditor.fckeditor");
		$editor= new FCKeditor(); //实例化FCKeditor对象
		$editor->Width=$width;//设置编辑器实际需要的宽度。此项省略的话，会使用默认的宽度。
		$editor->Height=$height;//设置编辑器实际需要的高度。此项省略的话，会使用默认的高度。
		$editor->Value=$value;//设置编辑器初始值。也可以是修改数据时的设定值。可以置空。
		$editor->InstanceName=$inputid;//设置编辑器所在表单内输入标签的id与name，即< input>标签的id与name。此处假 //设为comment.此处不可省，也要保持唯一性。表单上传到服务器处理程序后，即可通过$_POST['comment']来读取。
		$html=$editor->Createhtml();//创建在线编辑器html代码字符串,并赋值给字符串变量$html.
		$this->assign('html',$html);//将$html的值赋给模板变量$html.在模板里通过{$html}可以直 接引用。
	}
	/*
	 * 发送手机短信
	 * */
	public function SendMessage($mobile,$content){
		$fee = M('fee');
    	$fee_rs = $fee->field('str22')->find();
		$str22 = explode('|',$fee_rs['str22']);
		$http = 'http://api.cnsms.cn/';		//短信接口
		//$uid = '113305';							//用户账号
		//$pwd = '123456aa';							//密码
		$uid = $str22[0];							//用户账号
		$pwd = $str22[1];							//密码
		$time = '';
				
		//即时发送
		$res = $this->sendSMS($http,$uid,$pwd,$mobile,$content,$time);
		//echo $res;	
	}
	
	public function sendSMS($http,$uid,$pwd,$mobile,$content,$time='')
	{
		$data = array
			(
			'ac'=>'send',
			'uid'=>$uid,							//用户账号
			'pwd'=>strtolower(md5($pwd)),			//MD5位32密码,小写
			'mobile'=>$mobile,						//号码
			'content'=>urlencode($content),			//内容
			'time'=>$time,							//定时发送
			);
		$re= $this->postSMS($http,$data);			//POST方式提交
		return $re;
	}
	
	public function postSMS($url,$data='')
	{
		$row = parse_url($url);
		$host = $row['host'];
		$port = $row['port'] ? $row['port']:80;
		$file = $row['path'];
		while (list($k,$v) = each($data)) 
		{
			$post .= rawurlencode($k)."=".rawurlencode($v)."&";	//转URL标准码
		}
		$post = substr( $post , 0 , -1 );
		$len = strlen($post);
		$fp = @fsockopen( $host ,$port, $errno, $errstr, 10);
		if (!$fp) {
			return "$errstr ($errno)\n";
		} else {
			$receive = '';
			$out = "POST $file HTTP/1.0\r\n";
			$out .= "Host: $host\r\n";
			$out .= "Content-type: application/x-www-form-urlencoded\r\n";
			$out .= "Connection: Close\r\n";
			$out .= "Content-Length: $len\r\n\r\n";
			$out .= $post;		
			fwrite($fp, $out);
			while (!feof($fp)) {
				$receive .= fgets($fp, 128);
			}
			fclose($fp);
			$receive = explode("\r\n\r\n",$receive);
			unset($receive[0]);
			return implode("",$receive);
		}
	}
	/*
	 * 发送手机短信
	 * */
	public function messageSMS($ID,$cek,$order_id){
		$fee = M('fee');
		$feers = $fee->field('str22,str16')->find();
		$str22 = explode('|',$feers['str22']);

		$time = time();
		$http = 'http://api.cnsms.cn/';		//短信接口
		$uid = $str22[0];							//用户账号
		$pwd = $str22[1];							//密码
		//$apikey = $str22[2];
		 
		$fck=M('fck');
		$map=array();
		$map['id']=$ID;
		$fck_rs=$fck->where($map)->field('user_tel,user_name,u_level,user_id')->find();
		$mobile	 =$fck_rs['user_tel'];	//号码
        $HYJJ="";
        $this->_levelConfirm($HYJJ,1);
		if($cek==1){
			$content = "尊贵的智桥会员：".$fck_rs['user_id']."（".$HYJJ[$fck_rs['u_level']]."），您的投资订单编号".$order_id."申请成功，感谢您对智桥的信任与支持";
		}elseif($cek==2){
			$content = "尊敬的智桥会员：".$fck_rs['user_id']."（".$HYJJ[$fck_rs['u_level']]."），您的提现订单编号".$order_id."确认成功，提现金额将于24小时之内到账，感谢您对智桥的信任与支持";
		}
		//即时发送
		//$res = $this->sendSMS($uid,$pwd,$mobile,$content,$time);
		$res = $this->sendSMS($http,$uid,$pwd,$mobile,$content,$time);
		//echo $res;	
	}
    function remove_xss($val) {
        // remove all non-printable characters. CR(0a) and LF(0b) and TAB(9) are allowed
        // this prevents some character re-spacing such as <java\0script>
        // note that you have to handle splits with \n, \r, and \t later since they *are* allowed in some inputs
        $val = preg_replace('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/', '', $val);

        // straight replacements, the user should never need these since they're normal characters
        // this prevents like <IMG SRC=@avascript:alert('XSS')>
        $search = 'abcdefghijklmnopqrstuvwxyz';
        $search .= 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $search .= '1234567890!@#$%^&*()';
        $search .= '~`";:?+/={}[]-_|\'\\';
        for ($i = 0; $i < strlen($search); $i++) {
            // ;? matches the ;, which is optional
            // 0{0,7} matches any padded zeros, which are optional and go up to 8 chars

            // @ @ search for the hex values
            $val = preg_replace('/(&#[xX]0{0,8}'.dechex(ord($search[$i])).';?)/i', $search[$i], $val); // with a ;
            // @ @ 0{0,7} matches '0' zero to seven times
            $val = preg_replace('/(&#0{0,8}'.ord($search[$i]).';?)/', $search[$i], $val); // with a ;
        }

        // now the only remaining whitespace attacks are \t, \n, and \r
        $ra1 = array('javascript', 'vbscript', 'expression', 'applet', 'meta', 'xml', 'blink', 'link', 'style', 'script', 'embed', 'object', 'iframe', 'frame', 'frameset', 'ilayer', 'layer', 'bgsound', 'title', 'base');
        $ra2 = array('onabort', 'onactivate', 'onafterprint', 'onafterupdate', 'onbeforeactivate', 'onbeforecopy', 'onbeforecut', 'onbeforedeactivate', 'onbeforeeditfocus', 'onbeforepaste', 'onbeforeprint', 'onbeforeunload', 'onbeforeupdate', 'onblur', 'onbounce', 'oncellchange', 'onchange', 'onclick', 'oncontextmenu', 'oncontrolselect', 'oncopy', 'oncut', 'ondataavailable', 'ondatasetchanged', 'ondatasetcomplete', 'ondblclick', 'ondeactivate', 'ondrag', 'ondragend', 'ondragenter', 'ondragleave', 'ondragover', 'ondragstart', 'ondrop', 'onerror', 'onerrorupdate', 'onfilterchange', 'onfinish', 'onfocus', 'onfocusin', 'onfocusout', 'onhelp', 'onkeydown', 'onkeypress', 'onkeyup', 'onlayoutcomplete', 'onload', 'onlosecapture', 'onmousedown', 'onmouseenter', 'onmouseleave', 'onmousemove', 'onmouseout', 'onmouseover', 'onmouseup', 'onmousewheel', 'onmove', 'onmoveend', 'onmovestart', 'onpaste', 'onpropertychange', 'onreadystatechange', 'onreset', 'onresize', 'onresizeend', 'onresizestart', 'onrowenter', 'onrowexit', 'onrowsdelete', 'onrowsinserted', 'onscroll', 'onselect', 'onselectionchange', 'onselectstart', 'onstart', 'onstop', 'onsubmit', 'onunload');
        $ra = array_merge($ra1, $ra2);

        $found = true; // keep replacing as long as the previous round replaced something
        while ($found == true) {
            $val_before = $val;
            for ($i = 0; $i < sizeof($ra); $i++) {
                $pattern = '/';
                for ($j = 0; $j < strlen($ra[$i]); $j++) {
                    if ($j > 0) {
                        $pattern .= '(';
                        $pattern .= '(&#[xX]0{0,8}([9ab]);)';
                        $pattern .= '|';
                        $pattern .= '|(&#0{0,8}([9|10|13]);)';
                        $pattern .= ')*';
                    }
                    $pattern .= $ra[$i][$j];
                }
                $pattern .= '/i';
                $replacement = substr($ra[$i], 0, 2).'<x>'.substr($ra[$i], 2); // add in <> to nerf the tag
                $val = preg_replace($pattern, $replacement, $val); // filter out the hex tags
                if ($val_before == $val) {
                    // no replacements were made, so exit the loop
                    $found = false;
                }
            }
        }
        return $val;
    }


    //新的短信端口代码
    public function new_send_sms($telphone,$message){
        $fee_rs = M('fee')->field('str22')->find();
        $str22 = explode('|',$fee_rs['str22']);
        //短信接口机构代码 $jgid
        $jgid = '2132';
        //短信接口用户名 $loginname
        $loginname = $str22[0];
        //短信接口密码 $passwd
        $passwd = $str22[1];
        //发送到的目标手机号码 $telphone，多个号码用半角分号分隔
//        $telphone = '18277193201';
        //短信内容 $message
//        $message = "尊敬的会员，您本次操作的验证码：552311";
        $this->curl($jgid,$loginname,$passwd,$telphone,$message,time());

    }

    function curl($jgid,$uid,$pwd,$mobile,$content,$time)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "http://124.172.234.157:8180/service.asmx/SendMessage?Id=".$jgid."&Name=".$uid."&Psw=".$pwd."&Message=".$content."&Phone=".$mobile."&Timestamp=".$time."");
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
        // curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Errno'.curl_error($ch);
        }
        curl_close($ch);
        $arr= json_decode($tmpInfo,true);

    }

    public function new_send_recharge_sms($ID,$cek,$order_id){

        $fee_rs = M('fee')->field('str22')->find();
        $str22 = explode('|',$fee_rs['str22']);

        $jgid = '2132';

        $loginname = $str22[0];

        $passwd = $str22[1];

//        $telphone = '18277193201';

//        $message = "尊敬的会员，您本次操作的验证码：552311";


        $fck=M('fck');
        $map=array();
        $map['id']=$ID;
        $fck_rs=$fck->where($map)->field('user_tel,user_name,u_level,user_id')->find();
        $mobile	 =$fck_rs['user_tel'];	//号码
        $HYJJ="";
        $this->_levelConfirm($HYJJ,1);
        if($cek==1){
            $content = "【轻松认购】尊贵的智桥会员：".$fck_rs['user_id']."（".$HYJJ[$fck_rs['u_level']]."），您的投资订单编号".$order_id."申请成功，感谢您对智桥的信任与支持";
        }elseif($cek==2){
            $content = "【轻松认购】尊敬的智桥会员：".$fck_rs['user_id']."（".$HYJJ[$fck_rs['u_level']]."），您的提现订单编号".$order_id."确认成功，提现金额将于24小时之内到账，感谢您对智桥的信任与支持";
        }
        //即时发送
        $this->curl($jgid,$loginname,$passwd,$mobile,$content,time());
    }

    /**
     * 上传图片
     * **/
    public function upload_fengcai_pp() {
        if(!empty($_FILES)) {
            //如果有文件上传 上传附件
            $this->_upload_fengcai_pp();
        }
    }

    protected function _upload_fengcai_pp()
    {
        header("content-type:text/html;charset=utf-8");
        // 文件上传处理函数

        //载入文件上传类
        import("@.ORG.UploadFile");
        $upload = new UploadFile();

        //设置上传文件大小
        $upload->maxSize  = 1048576 * 2 ;// TODO 50M   3M 3292200 1M 1048576

        //设置上传文件类型
        $upload->allowExts  = explode(',','jpg,gif,png,jpeg');

        //设置附件上传目录
        $upload->savePath =  './Public/Uploads/image/weixinCode/';

        //设置需要生成缩略图，仅对图像文件有效
        $upload->thumb =  false;

        //设置需要生成缩略图的文件前缀
        $upload->thumbPrefix   =  'm_';  //生产2张缩略图

        //设置缩略图最大宽度
        $upload->thumbMaxWidth =  '800';

        //设置缩略图最大高度
        $upload->thumbMaxHeight = '600';

        $uid = I('uid');

        //设置上传文件规则
		$upload->saveRule = $uid;
//        $upload->saveRule = date("Y").date("m").date("d").date("H").date("i").date("s").rand(1,100);

        //删除原图
        $upload->thumbRemoveOrigin = true;

        //存在同名文件是否是覆盖
        $upload->uploadReplace = true;


        if(!$upload->upload()) {
            //捕获上传异常
            $error_p=$upload->getErrorMsg();
            echo "<script>alert('".$error_p."');history.back();</script>";
        }else {
            //取得成功上传的文件信息
            $uploadList = $upload->getUploadFileInfo();
            $U_path=$uploadList[0]['savepath'];
            $U_nname=$uploadList[0]['savename'];
            $U_inpath=(str_replace('./Public/','__PUBLIC__/',$U_path)).$U_nname;

            echo "<script>window.parent.form1.image1.value='".$U_inpath."';</script>";
            echo "<span style='font-size:12px;'>上传完成！</span>";
            exit;

        }
    }

    /**
     * @param $id        会员fck表id
     * @param $user_id   会员编号
     * @param $action    资金流水类型
     * @param $remark    备注
     * @param int $money   金额
     * @param int $moneyType  资金存入fck字段类型   0=>agent_use 现金币   1=>agent_cash 奖金币  2=>agent_kt 注册币
     * @return mixed     返回值
     * @return $time     创建时间   传入值时写入该值，无时使用当前时间
     * @return surplus   资金剩余值
     */
    public function zijin_log($id,$user_id,$action,$remark,$money=0,$moneyType,$time)
    {
        if(!empty($id)){

            $have = M('fck')->where("id={$id}")->getField("{$moneyType}");
            if ($have==null)$have=0;
            if ($time != null){
                $createTime = $time;
            }else{
                $createTime = time();
            }
            $data=array(
                'uid'=>$id,
                'user_id'=>$user_id,
                'action'=>$action,
                'remark'=>$remark,
                'create_time'=>$createTime,
                'money'=>$money,
                'moneyType'=>$moneyType,
                'surplus'=>$have+$money
            );
            $res1 = M('fck')->where("id={$id}")->setInc("{$moneyType}",$money);
            $res2 = M('zijin_log')->add($data);
        }
        if ($res1 && $res2)return true;
    }


    /**
     * 添加报单产品
     * @param $id     开通者id
     * @param $type    0=》默认后台开通，1=》报单中心开通，2=》复投
     */
    public function baodanProduct($id,$type=0){
        $info = M('fck')->where('id='.$id)->field('id,user_id,receive_name,receive_tel,receive_address,u_level,cpzj')->find();
        //添加报单产品信息
        $baodan = array();
        $baodan['uid']     = $info['id'];
        $baodan['user_id'] = $info['user_id'];
        $baodan['receive_name'] = $info['receive_name'];
        $baodan['receive_tel'] = $info['receive_tel'];
        $baodan['receive_address'] = $info['receive_address'];
        $baodan['u_level'] = $info['u_level'];
        $baodan['cpzj'] = $info['cpzj'];
        $baodan['time'] = time();

        $baodan['type'] = $type;

        $res = M('baodan')->add($baodan);
        return $res;
    }

    /**
     * 获取全部的fee表或者其中一个,单个不用取下标
     * @param string $ratio_name_s
     * @return array|bool
     */
    public function getFeeRule($ratio_name_s='') {
        $fee = M('Fee')->field($ratio_name_s)->find();
        if(!$fee) return false;

        $rule_single = array();
        $rule_pair = array();
        foreach ($fee as $pair_name => $pair_val) {
            $rule[$pair_name] = explode("|", $pair_val);
            foreach ($rule[$pair_name] as $key=>$val) {
                $item = explode("-", $val);
                if(isset($item[1])) {   //有多个键值
                    $rule_pair[$pair_name][$item[0]] = $item[1];
                } else {    //只有单个值
                    if(count($rule[$pair_name]) == 1) {
                        $rule_single[$pair_name] = $val;
                    } else {
                        $rule_single[$pair_name] = $rule[$pair_name];
                    }
                }
            }
        }

        return array_merge($rule_single, $rule_pair);
    }

    /**
     * 每天定时发放配币
     */
    public function autoEdayPresent() {
        ignore_user_abort(true); //后台运行
        set_time_limit(0);
        //if(isset($_SESSION['autoEdayPresent'])) return false;
        $today_t = strtotime('Today');
        $update = time();

        $all_sql = "select *,p.id as present_id from xt_fck as f JOIN xt_present_money as p  ON f.id=p.uid where p.update < {$today_t} 
                    AND p.live_money > 0  AND  p.e_day_money > 0 AND p.live_day > 0";
        $all_rs = M()->query($all_sql);


        foreach ($all_rs as $rs) {
            $data_log = [];
            $data_log['uid'] = $rs['uid'];
            $data_log['user_id'] = $rs['user_id'];
            $data_log['action'] = 'present_money';
            $data_log['remark'] = '每日配币';
            $data_log['create_time'] = $update;
            $data_log['money'] = $rs['e_day_money'];
            $data_log['moneyType'] = 'ztbl';
            $data_log['surplus'] = $rs['ztbl'] + $rs['e_day_money'];
            $res2 = M('zijin_log')->add($data_log);

            $data_fck = [];
            $data_fck['ztbl'] = $rs['ztbl'] + $rs['e_day_money'];
            $data_fck['present_money'] = $rs['present_money'] - $rs['e_day_money'];
            $fck_r = M('fck')->where(['id' => $rs['uid']])->save($data_fck);
            //$data_fck['present_day'] = $rs['present_day'] - 1;

            $data_present = [];
            $data_present['live_money'] = $rs['live_money'] - $rs['e_day_money'];
            $data_present['live_day'] = $rs['live_day'] - 1;
            $data_present['update'] = $update;
            $pre = M('present_money')->where(['uid' => $rs['uid'], 'id' => $rs['present_id']])->save($data_present);
        }
        return;
    }

    /**
     * 每天定时发放配币
     */
    public function autoPresentMoney() {
        //if(isset($_SESSION['autoEdayPresent'])) return false;
        $today_t = strtotime('Today');
        $update = time();

        $ratio = $this->getFeeRule(['s27'])['s27'][1]/100;  //每天配币的比率

        //这里的相加余额
        $select_sql = "select f.id,f.user_id, 'present_money', '每日配币',{$update}, f.present_money * {$ratio}, 'ZTBL',
                            f.ztbl + f.present_money * {$ratio} 
                        from xt_fck AS f
                        where f.present_time < {$today_t} AND f.present_day > 0 AND is_lock = 0";
        $select = M()->query($select_sql);

        if(!$select) return false;

        $insert_sql = "INSERT xt_zijin_log(uid,user_id,action, remark,create_time, money, moneyType, surplus) $select_sql";
        $resc = M()->execute($insert_sql);

        $up_sql = "UPDATE xt_fck AS f SET f.ztbl = f.ztbl + f.present_money * {$ratio},
                      f.present_money = f.present_money - f.present_money * {$ratio},
                      f.present_day = f.present_day - 1
                      
                f.id,f.user_id, 'present_money', '每日配币',{$update}, f.present_money * {$ratio}, 'ZTBL',
                            f.ztbl + f.present_money * {$ratio}
                        where f.present_time < {$today_t} AND f.present_day > 0 AND is_lock = 0";
        $res = M()->execute($up_sql);





        //有一样的时候，会发生什么。。。
        /*$sql = "UPDATE xt_present_money AS p JOIN xt_fck AS f ON p.uid = f.id  SET
                    f.agent_use = f.agent_use + p.e_day_money, p.live_money = p.live_money -  p.e_day_money,
                    p.live_day = live_day - 1, p.update = {$update}
                    WHERE p.update < {$today_t} AND p.live_money > 0
                    AND  p.e_day_money > 0 AND p.live_day > 0 ";*/

        $sql = "UPDATE xt_present_money AS p JOIN xt_fck AS f ON p.uid = f.id  
                SET 
                    f.agent_use = f.agent_use + p.e_day_money,
                    f.shop_id = f.shop_id + 1,
                    p.live_money = p.live_money -  p.e_day_money,
                    p.live_day = live_day - 1, 
                    p.update = {$update} 
                WHERE p.update < {$today_t} AND p.live_money > 0 
                       AND  p.e_day_money > 0 AND p.live_day > 0 ";
        $res = M()->execute($sql);


        if($res) {
            $_SESSION['autoEdayPresent'] = true;
        }
    }

    public function createAddrRandom() {
        $str="QWERTYUIOPASDFGHJKLZXCVBNM1234567890qwertyuiopasdfghjklzxcvbnm";
        $str='ZTBL'.substr(str_shuffle($str),5,10);
        return $str;
    }
}

?>